package controller

import (
	"bytes"
	"fmt"
	"fx_swift_boss/api"
	"fx_swift_boss/internal/service"
	"fx_swift_boss/pkg/code"
	"fx_swift_boss/pkg/global"
	"fx_swift_boss/pkg/internalerrors"
	"fx_swift_boss/pkg/logger"
	"fx_swift_boss/pkg/upload"
	"github.com/gin-gonic/gin"
	"github.com/golang-module/carbon/v2"
	"github.com/spf13/cast"
	"github.com/xuri/excelize/v2"
	"net/http"
)

// 卡管理列表
func CardList(c *gin.Context) {
	req := &api.CardListReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		code.Fail(c, http.StatusBadRequest, code.ErrEncodingJSON, err.Error())
		return
	}
	result, err := service.NewCardSrv().CardList(c, req)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, result)
	}
}

// 卡详情
func GetCardDetails(c *gin.Context) {
	cardId := c.Query("card_id")
	result, err := service.NewCardSrv().GetCardDetails(c, cardId)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, result)
	}
}

// 操作卡状态
func OperatorCardState(c *gin.Context) {
	cardId := c.Query("card_id")
	state := c.Query("state")
	err := service.NewCardSrv().OperatorCardState(c, state, cardId)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, nil)
	}
}

// 卡交易列表
func CardTradeList(c *gin.Context) {
	req := &api.CardTradeListReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		code.Fail(c, http.StatusBadRequest, code.ErrEncodingJSON, err.Error())
		return
	}
	result, err := service.NewCardSrv().CardTradeList(c, req)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, result)
	}
}

// 卡图查询
func GetCardImage(c *gin.Context) {
	cardId := c.Query("card_id")
	result, err := service.GetCardImage(c, cardId)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, result)
	}
}

// 宝付账户余额
func BossAccount(c *gin.Context) {
	ccy := c.Query("ccy")
	result, err := service.NewCardSrv().BossAccount(c, ccy)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, result)
	}
}

func ExportCardTrade(c *gin.Context) {
	var (
		err      error
		filePath string
		// 获取最大导出数
		maxNum  = global.ViperObj.GetInt("export.maxNum")
		account = c.GetString("Account")
		line    = 1
	)
	logger.SugarLogger.Infof("开始时间为：%s", carbon.Now().ToDateTimeString())
	req := &api.CardTradeListReq{}
	if err = c.ShouldBindJSON(&req); err != nil {
		code.Fail(c, http.StatusBadRequest, code.ErrEncodingJSON, err.Error())
		return
	}
	req.PageSize = cast.ToUint64(maxNum)
	result, err := service.NewCardSrv().CardTradeList(c, req)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, code.ErrEncodingJSON, err.Error())
		return
	}

	f := excelize.NewFile() // 设置单元格的值
	index, _ := f.NewSheet("Sheet1")
	// 这里设置表头
	f.SetCellValue("Sheet1", "A1", "交易流水号")
	f.SetCellValue("Sheet1", "B1", "卡号")
	f.SetCellValue("Sheet1", "C1", "持卡人")
	f.SetCellValue("Sheet1", "D1", "卡别名")
	f.SetCellValue("Sheet1", "E1", "交易金额")
	f.SetCellValue("Sheet1", "F1", "交易金额(换算为该卡币种)")
	f.SetCellValue("Sheet1", "G1", "交易类型")
	f.SetCellValue("Sheet1", "H1", "交易时间")
	f.SetCellValue("Sheet1", "I1", "企业名称")
	f.SetCellValue("Sheet1", "J1", "交易状态")

	if len(result.List) > maxNum {
		code.Fail(c, http.StatusBadRequest, code.ErrCanNotOpenFile, "导出数据太多，请分批导出")
		return
	}
	// 循环写入数据
	for _, v := range result.List {
		line++
		f.SetCellValue("Sheet1", fmt.Sprintf("A%d", line), v.TradeNo)
		f.SetCellValue("Sheet1", fmt.Sprintf("B%d", line), v.CardNo)
		f.SetCellValue("Sheet1", fmt.Sprintf("C%d", line), v.FirstName+v.LastName)
		f.SetCellValue("Sheet1", fmt.Sprintf("D%d", line), v.CardAlias)
		f.SetCellValue("Sheet1", fmt.Sprintf("E%d", line), v.Amount+v.Currency)
		f.SetCellValue("Sheet1", fmt.Sprintf("F%d", line), v.LocalAmount+v.LocalCurrency)
		if v.TradeType == "AUTH" {
			f.SetCellValue("Sheet1", fmt.Sprintf("G%d", line), "消费")
		} else if v.TradeType == "REVERSAL" {
			f.SetCellValue("Sheet1", fmt.Sprintf("G%d", line), "冲正")
		} else if v.TradeType == "REFUND" {
			f.SetCellValue("Sheet1", fmt.Sprintf("G%d", line), "退款")
		} else if v.TradeType == "FEE" {
			f.SetCellValue("Sheet1", fmt.Sprintf("G%d", line), "手续费")
		} else if v.TradeType == "FEE_REVERSAL" {
			f.SetCellValue("Sheet1", fmt.Sprintf("G%d", line), "手续费冲正")
		} else if v.TradeType == "ORIGINAL_CREDIT" {
			f.SetCellValue("Sheet1", fmt.Sprintf("G%d", line), "OCT退款")
		} else if v.TradeType == "ORIGINAL_CREDIT_REVERSAL" {
			f.SetCellValue("Sheet1", fmt.Sprintf("G%d", line), "OCT退款冲正")
		}

		f.SetCellValue("Sheet1", fmt.Sprintf("H%d", line), v.TradeTime)
		f.SetCellValue("Sheet1", fmt.Sprintf("I%d", line), v.CompanyName)
		if v.State == "APPROVED" {
			f.SetCellValue("Sheet1", fmt.Sprintf("J%d", line), "成功")
		} else if v.State == "DECLINED" {
			f.SetCellValue("Sheet1", fmt.Sprintf("J%d", line), "拒绝")
		}

	}

	f.SetActiveSheet(index)

	var buffer bytes.Buffer
	_ = f.Write(&buffer)
	content := bytes.NewReader(buffer.Bytes())

	fileName := fmt.Sprintf("download/%s%s%s.xlsx", account, `-`, "exportCashFlow")
	if filePath, err = upload.UploadToS3Srv(fileName, content); err != nil || len(filePath) == 0 {
		code.Fail(c, http.StatusBadRequest, code.ErrCanNotOpenFile, err.Error())
		return
	}
	logger.SugarLogger.Infof("结束时间为：%s", carbon.Now().ToDateTimeString())
	code.Success(c, filePath)
}
